import com.fasterxml.jackson.databind.ObjectMapper;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.LinkedHashMap;

/**
 * @Author quan
 * @Description Servlet实现一个计算器: ajax的形式
 * @Date 2023/6/23 17:43
 */

/**
 * ajax版本
 */
@WebServlet("/calculator_ajax")
public class Calculator_ajax extends HttpServlet {
    //定义成类属性，且不能被修改
    private final ObjectMapper objectMapper = new ObjectMapper();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req,resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //-------------------------与form形式的不同点1--------------------------
        //0、设置返回的数据类型和编码：设置为json格式
        req.setCharacterEncoding("UTF-8");
        resp.setContentType("application/json;charset=utf-8");
        //1、从请求req中获取参数num1
        String num1 = req.getParameter("num1");
        String num2 = req.getParameter("num2");
        //2、参数的合法性校验
        if(num1==null || num1.equals("") || num2==null || num2.equals("")){
            //直接返回错误信息
            resp.getWriter().write("抱歉，参数有误");
        }
        //3、进行类型转换String-int
        int number1 = Integer.valueOf(num1);
        int number2 = Integer.valueOf(num2);
        //4、计算相加的结果
        int res = number1+number2;
        //---------------与form形式的不同点2-----------------------
        //5、返回json格式的对象
        //方式1：直接拼:要使用转义字符(不推荐，容易出错)
//        String jsonRes = "{\"code\":200, \"msg\":\"\", \"data\":"+res+"}";
//        resp.getWriter().write(jsonRes);
        //方式2：json工具：将一个字符串转为对象，或者将一个对象转为json字符串
        LinkedHashMap<String,Object> map = new LinkedHashMap<String, Object>();
        map.put("code",200);
        map.put("msg","");
        map.put("data",res);
        //返回结果
        String jsonStr = objectMapper.writeValueAsString(map);
        resp.getWriter().write(jsonStr);
     }
}
